import os
import yaml
from pathlib import Path
from typing import Dict, Any
from dotenv import load_dotenv

class Config:
    _instance = None
    _config: Dict[str, Any] = {}

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Config, cls).__new__(cls)
            cls._instance._load_config()
        return cls._instance

    def _load_config(self):
        """加载配置文件和环境变量"""
        # 加载环境变量
        load_dotenv()

        # 获取配置文件路径
        config_path = Path(__file__).parent.parent.parent / 'config' / 'config.yaml'
        
        # 读取配置文件
        with open(config_path, 'r', encoding='utf-8') as f:
            self._config = yaml.safe_load(f)

        # 使用环境变量覆盖配置
        self._override_from_env()

    def _override_from_env(self):
        """使用环境变量覆盖配置"""
        # 数据库配置
        if os.getenv('DATABASE_URL'):
            self._config['database']['url'] = os.getenv('DATABASE_URL')

        # 邮件配置
        if os.getenv('SMTP_SERVER'):
            self._config['notification']['email']['smtp_server'] = os.getenv('SMTP_SERVER')
        if os.getenv('SMTP_PORT'):
            self._config['notification']['email']['smtp_port'] = int(os.getenv('SMTP_PORT'))
        if os.getenv('SMTP_USERNAME'):
            self._config['notification']['email']['username'] = os.getenv('SMTP_USERNAME')
        if os.getenv('SMTP_PASSWORD'):
            self._config['notification']['email']['password'] = os.getenv('SMTP_PASSWORD')
        if os.getenv('EMAIL_FROM'):
            self._config['notification']['email']['from_addr'] = os.getenv('EMAIL_FROM')
        if os.getenv('EMAIL_TO'):
            self._config['notification']['email']['to_addrs'] = os.getenv('EMAIL_TO').split(',')

        # 微信配置
        if os.getenv('WECHAT_CORP_ID'):
            self._config['notification']['wechat']['corp_id'] = os.getenv('WECHAT_CORP_ID')
        if os.getenv('WECHAT_CORP_SECRET'):
            self._config['notification']['wechat']['corp_secret'] = os.getenv('WECHAT_CORP_SECRET')
        if os.getenv('WECHAT_AGENT_ID'):
            self._config['notification']['wechat']['agent_id'] = os.getenv('WECHAT_AGENT_ID')
        if os.getenv('WECHAT_TO_USER'):
            self._config['notification']['wechat']['to_user'] = os.getenv('WECHAT_TO_USER')

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        try:
            keys = key.split('.')
            value = self._config
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default

config = Config() 